package restore

import (
	"encoding/json"
	"fmt"
	"mariadb-operator/pkg/apis/finupgroup/v1alpha1"
	"mariadb-operator/pkg/constants"
	"os"

	"github.com/streadway/amqp"
)

// ProduceTask produce restore task and then send to mq
func ProduceTask(r *v1alpha1.RestoreTask) error {
	mq := os.Getenv("RABBIT_MQ")
	conn, err := amqp.Dial(mq)
	if err != nil {
		return fmt.Errorf("Failed to connect to RabbitMQ : %v", err)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		return fmt.Errorf("Failed to open a channel : %v", err)
	}
	defer ch.Close()

	q, err := ch.QueueDeclare(
		constants.RestoreTaskQueueName, // name
		false, // durable
		false, // delete when unused
		false, // exclusive
		false, // no-wait
		nil,   // arguments
	)
	if err != nil {
		return fmt.Errorf("Failed to declare a queue : %v", err)
	}

	body, err := json.Marshal(r)
	if err != nil {
		return fmt.Errorf("Failed to marshal restore task : %v", err)
	}
	err = ch.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "application/json",
			Body:        []byte(body),
		})
	if err != nil {
		return fmt.Errorf("Failed to send restore task to mq : %v", err)
	}
	return nil
}
